﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using QLKS.Templates;
using System.Data;
using Infragistics.Windows.DataPresenter;
using System.Windows.Threading;
using System.Collections.ObjectModel;
using System.ComponentModel;
using QLKS.ViewModels;

namespace QLKS.Views
{
    /// <summary>
    /// Interaction logic for frmThanhToan.xaml
    /// </summary>
    public partial class frmThanhToan : FormTrans
    {
        
        public bool UpdateSucces = false;
        Command cm = Command.None;
        ViewModels.PhongViewModel Phong = null;
        DataTable tbTemp = new DataTable();
        string curentMaPhong = string.Empty;
        BindingList<ThanhToanViewModel> Data = new BindingList<ThanhToanViewModel>();
        //bool newrow = true;
        public bool IsEditMode
        {
            get { return (bool)GetValue(IsEditModeProperty); }
            set { SetValue(IsEditModeProperty, value); }
        }

        // Using a DependencyProperty as the backing store for IsEditMode.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsEditModeProperty =
            DependencyProperty.Register("IsEditMode", typeof(bool), typeof(frmThanhToan), new UIPropertyMetadata(true));


        public DataTable tbDmPhong
        {
            get { return (DataTable)GetValue(tbDmPhongProperty); }
            set { SetValue(tbDmPhongProperty, value); }
        }

        // Using a DependencyProperty as the backing store for tbDmPhong.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty tbDmPhongProperty =
            DependencyProperty.Register("tbDmPhong", typeof(DataTable), typeof(frmThanhToan), new UIPropertyMetadata(null));

        public DataTable tb
        {
            get { return (DataTable)GetValue(tbProperty); }
            set { SetValue(tbProperty, value); }
        }

        // Using a DependencyProperty as the backing store for tb.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty tbProperty =
            DependencyProperty.Register("tb", typeof(DataTable), typeof(frmThanhToan), new UIPropertyMetadata(new DataTable()));

        public DataTable tbKhachHang
        {
            get { return (DataTable)GetValue(tbKhachHangProperty); }
            set { SetValue(tbKhachHangProperty, value); }
        }

        // Using a DependencyProperty as the backing store for tbKhachHang.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty tbKhachHangProperty =
            DependencyProperty.Register("tbKhachHang", typeof(DataTable), typeof(frmThanhToan), new UIPropertyMetadata(ViewModels.KhachHangViewModel.GetAllKhachHang()));



        public double TongTien
        {
            get { return (double)GetValue(TongTienProperty); }
            set { SetValue(TongTienProperty, value); }
        }

        // Using a DependencyProperty as the backing store for TongTien.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TongTienProperty =
            DependencyProperty.Register("TongTien", typeof(double), typeof(frmThanhToan), new UIPropertyMetadata(null));


        public frmThanhToan()
        {
            InitializeComponent();
        }

        //Khởi tạo
        public frmThanhToan(ViewModels.PhongViewModel _phong, Command _cm)
        {
            InitializeComponent();
            cm = _cm;
            IsEditMode = _cm == Command.View ? false : true;
        }

        //Thêm dòng mới
        private void AddNewRow(int stt)
        {
            Data.Add(new ThanhToanViewModel(stt,null, DateTime.Now.ToString("dd/MM/yyyy"),null, 0, 0, 0,0,false));
            xdgDsPhong.Focus();
            xdgDsPhong.ActiveCell = (xdgDsPhong.Records[stt-1] as DataRecord).Cells["MaPhong"];
        }

        //Xóa dòng
        private void DeleteRow(int stt)
        {
            tb.Rows.RemoveAt(stt);
        }

        private void txtTextboxComplete_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "IsReadOnly")
                return;
            if (xdgDsPhong.ActiveCell == null)
                return;
            if (xdgDsPhong.ActiveCell.Value == null)
                return;
            DataRow[] row = tbDmPhong.Select("maphong like'" + xdgDsPhong.ActiveCell.Value.ToString() + "'");

            if (row.Length > 0)
            {
                UpdateDsPhong(row[0]["maphong"].ToString(), 1);
                
            }
        }

        //Update Datagrid
        private void UpdateDsPhong(string maphong, int type)
        {
            try
            {
                DataTable _tb = ViewModels.ThuePhongViewModel.GetChiTietPhongThue(maphong, "matp,maphong,ngaythue,giothue,giatheongay,giatheogio,loaithue");
                int songaythue = DateTime.Now.DayOfYear - DateTime.Parse(_tb.Rows[0]["ngaythue"].ToString()).DayOfYear;
                songaythue = songaythue == 0 ? 1 : songaythue;
                int sogiothue = DateTime.Now.Hour + (songaythue * 24) - TimeSpan.Parse(_tb.Rows[0]["giothue"].ToString()).Hours;
                sogiothue = sogiothue == 0 ? 1 : sogiothue;
                if (type == 0)
                {
                    //tb.Rows.Add(tb.Rows.Count + 1, _tb.Rows[0]["maphong"], DateTime.Parse(_tb.Rows[0]["ngaythue"].ToString()).ToString("dd/MM/yyyy"), DateTime.Now.ToString("dd/MM/yyyyy"), songaythue, sogiothue, _tb.Rows[0]["giatheongay"], _tb.Rows[0]["giatheogio"]);
                    Data.Add(new ThanhToanViewModel(Data.Count + 1,_tb.Rows[0]["maphong"].ToString(), DateTime.Parse(_tb.Rows[0]["ngaythue"].ToString()).ToString("dd/MM/yyyy"), DateTime.Now.ToString("dd/MM/yyyy"), songaythue, sogiothue, double.Parse(_tb.Rows[0]["giatheongay"].ToString()), double.Parse(_tb.Rows[0]["giatheogio"].ToString()),false));
                }
                else
                {
                    int dong = Data.Count - 1;
                    Data[dong].NgayThue = DateTime.Parse(_tb.Rows[0]["ngaythue"].ToString()).ToString("dd/MM/yyyy");
                    Data[dong].NgayTra = DateTime.Now.ToString("dd/MM/yyyy");
                    Data[dong].SoNgayThue = songaythue;
                    Data[dong].SoGioThue = sogiothue;
                    Data[dong].GiaTheoNgay = double.Parse(_tb.Rows[0]["giatheongay"].ToString());
                    Data[dong].GiaTheoGio = double.Parse(_tb.Rows[0]["giatheogio"].ToString());
                }
                xdgDsPhong.DataSource = Data;
                //if (CurentRow != null)
                //{
                List<TextBoxComplete> contentHost = SysLib.SysObj.FindListChild<TextBoxComplete>(xdgDsPhong, "UcTextBoxComplete");
                curentMaPhong = maphong;
                if (contentHost.Count > 0)
                {
                    contentHost[contentHost.Count - 1].IsReadOnly = true;
                    DataRow[] r = tbDmPhong.Select("maphong = '" + curentMaPhong + "'");
                    if (r.Length > 0)
                        tbDmPhong.Rows.Remove(r[0]);
                }
                //}
                double hesophuthu = Models.ThanhToanModel.GetHeSoPhuThu(maphong);
                string loaithue = _tb.Rows[0]["loaithue"].ToString();
                double Gia = loaithue == "0"?double.Parse(_tb.Rows[0]["giatheogio"].ToString()) * sogiothue:double.Parse(_tb.Rows[0]["giatheongay"].ToString()) * songaythue;
                Data[Data.Count - 1].TongTien = Gia * hesophuthu;
                TongTien += Data[Data.Count - 1].TongTien;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "QLKS", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        //Update 

        //Form Load
        private void FrmThanhToan_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                Phong = (ViewModels.PhongViewModel)DataContext;
                tbKhachHang = ViewModels.KhachHangViewModel.GetAllKhachHang("makh,tenkh,cmnd,diachi");
                tbDmPhong = ViewModels.PhongViewModel.GetDmPhong("maphong,tenlp", "tinhtrang = 2");
                tbTemp = tbDmPhong.Copy();
                xdgDsPhong.DataSource = Data;

                tbMain.Cm_Apply += new ucXToolBar.Execute(tbMain_Cm_Apply);
                tbMain.Cm_Exit += new ucXToolBar.Execute(tbMain_Cm_Exit);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "QLKS");
            }
            txtKhachHang.GetFocus();
        }
        //Kiểm tra thông tin
        private bool KiemTra()
        {
            if (txtKhachHang.ValueItem == null)
            {
                MessageBox.Show(M_LAN.Equals("V") ? "Chưa nhập tên khách hàng!" : "Please input customer name", "QLKS", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
            return true;
        }

        //Tực hiện thanh toán
        void tbMain_Cm_Apply()
        {
            if (KiemTra())
            {
                if (MessageBox.Show(M_LAN.Equals("V") ? "Có chắc bạn muốn thực hiện thanh toán không?" : "are you sure to perform payment", "QLKs", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
                    return;
                foreach (ViewModels.ThanhToanViewModel p in Data)
                    Models.ThanhToanModel.ThanhToanPhong(p.MaPhong, DateTime.Now.ToString("yyyyMMdd"), DateTime.Now.ToString("HH:mm:ss"), p.TongTien, txtKhachHang.ValueItem.ToString());
                MessageBox.Show(M_LAN.Equals("V") ? "Thanh toán thành công!" : "Perfrom successful", "QLKS", MessageBoxButton.OK, MessageBoxImage.Error);
                this.Close();
            }
        }

        //Exit
        void tbMain_Cm_Exit()
        {
            this.Close();          
        }

        //Thêm khách hàng mới
        private void txtKhachHang_AddNewItem(object sender, RoutedEventArgs e)
        {
            frmThemKhachHang frm = new frmThemKhachHang(null, Command.New);
            frm.ShowDialog();
            if (frm.UpdateSucces)
                tbKhachHang = ViewModels.KhachHangViewModel.GetAllKhachHang();
        }

        //Khách hàng changce
        private void txtKhachHang_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            DataRow[] row = tbKhachHang.Select("makh like'" + txtKhachHang.ValueItem + "'");

            if (row.Length > 0)
            {
                txtDiaChi.Text = row[0]["diachi"].ToString();
                UpdateDsPhong(Phong.MaPhong, tb.Rows.Count);
                DataRow[] r = tbDmPhong.Select("maphong = '" + Phong.MaPhong + "'");
                if (r.Length > 0)
                    tbDmPhong.Rows.Remove(r[0]);
            }
        }

        //dia chỉ focus
        private void txtDiaChi_GotFocus(object sender, RoutedEventArgs e)
        {
            txtDiaChi.SelectAll();
        }

        //Keydown
        private void FrmThanhToan_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.F4)
            {
                if (Data.Count > 0)
                    AddNewRow(Data.Count + 1);
                else
                    MessageBox.Show(M_LAN.Equals("V") ? "Chưa vào tên khách hàng!" : "Input customer name, please!","QLKS", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        //Command delete
        public static RoutedCommand DeleteCommand = new RoutedCommand();
        private void DeleteCanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
            e.Handled = true;
        }

        private void DeleteExecute(object sender, ExecutedRoutedEventArgs e)
        {
            if (Data.Count <= 1)
            {
                MessageBox.Show(M_LAN.Equals("V") ? "Không thể xóa phòng này!" : "Can't delete this room!", "QLKS", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            DataRecord dr = this.xdgDsPhong.ActiveRecord as DataRecord;
            if (dr == null) return;

            BindingList<ThanhToanViewModel> dataSource = this.xdgDsPhong.DataSource as BindingList<ThanhToanViewModel>;
            if (dataSource == null) return;

            dataSource.Remove(dr.DataItem as ThanhToanViewModel);
            e.Handled = true;
        }

        //Xóa phòng
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            int n = Data.Count;
            for (int i = 0; i < n; i++)
            {
                if (Data[i].Xoa == true)
                {
                    if (i == 0)
                    {
                        Data[i].Xoa = false;
                        continue;
                    }
                    DataRow[] r = tbTemp.Select("maphong = '" + Data[i].MaPhong + "'");
                    if (r.Length > 0)
                        tbDmPhong.Rows.Add(r[0].ItemArray);
                    Data.RemoveAt(i);
                    i--;
                    n--;

                }
            }
        }

        private void xdgDsPhong_PreviewGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            if(e.NewFocus is XamDataGrid)
            {
                if (Data.Count >= 1)
                {
                    xdgDsPhong.ActiveCell = (xdgDsPhong.Records[0] as DataRecord).Cells["MaPhong"];
                    TextBoxComplete contentHost = SysLib.SysObj.FindChild<TextBoxComplete>(xdgDsPhong.ActiveCell.DataPresenter, "UcTextBoxComplete");
                    if (contentHost != null)
                        contentHost.IsReadOnly = true;
                }
            }
        }

        private void xdgDsPhong_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Up && e.Key != Key.Down && e.Key != Key.Enter && e.Key != Key.Tab)
            {
                if (xdgDsPhong.ActiveCell.Field.Name == "MaPhong")
                {
                    object contentHost = SysLib.SysObj.FindChild<TextBoxComplete>((e.OriginalSource as CellValuePresenter), "UcTextBoxComplete");
                    if (contentHost != null)
                        (contentHost as TextBoxComplete).GetFocus();
                }
            }
        }

    }
}
